package com.bems.action;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;

import cn.org.ape.BaseAction;

import com.bems.common.UtilEnum;
import com.bems.jdbc.common.DBManager;
import com.bems.pojo.Code;
import com.bems.pojo.List;
import com.bems.pojo.POJO;
import com.bems.pojo.User;
import com.bems.service.ListService;
import com.bems.util.PageUtil;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.oreilly.servlet.multipart.FilePart;
import com.oreilly.servlet.multipart.MultipartParser;
import com.oreilly.servlet.multipart.ParamPart;
import com.oreilly.servlet.multipart.Part;

public class ListAction extends BaseAction
{
	ListService listService = new ListService();
	private int limit;
	private int page;
	private String status;
	private String type;
	private List list;

	
	/*
	 * 出库清单/报废
	 */
	public void out()
	{
		User user=(User) session.getAttribute("user");
		if(user==null)
		{
				printHtml("请登录！");
				return; //判断用户是否登录 如果登录过期 返回
		}
		list.setAdmin_id(user.getId());
		list.setWarehouse_id(Long.parseLong(request.getParameter("warehouse_id")));// 库房
		//list.setStatus(Integer.parseLong(request.getParameter("setWarehouse_id")));
		list.setUser_id(Long.parseLong(request.getParameter("user_id")));
		list.setType_id(Long.parseLong(request.getParameter("type_id")));
		//list.setSupply_id(Long.parseLong(request.getParameter("supply_id")));
		if(list.Type().getIscode()==UtilEnum.Type_Iscode.Iscode.getValue())
		{
			java.util.List<String> lists = (java.util.List<String>) session.getAttribute("code");
			java.util.List<Code> codes = new ArrayList<Code>();;
			if(lists!=null)
			{
				for (String string : lists) {
					String[] s = StringUtils.split(string, " ");
					Code code = new Code();
					code.setNumber(s[0]);
					codes.add(code);
				}
			}
			
			if(listService.out(list, codes ))
			{
				printHtml("操着成功！");
			}
			else {
					printHtml("失败！");
			}
		}else {
			if(listService.out(list, null))
			{
				printHtml("操着成功！");
			}
			else {
					printHtml("失败！");
			}
		}
		
	}
	
	
	/**
	 * 入库、回库
	 */
	public void add()
	{
		User user=(User) session.getAttribute("user");
		if(user==null)
		{
			printHtml("请登录！");
				return; //判断用户是否登录 如果登录过期 返回
		}
		list.setAdmin_id(user.getId());
		list.setWarehouse_id(request.getParameter("warehouse_id")!=null?Long.parseLong(request.getParameter("warehouse_id")):null);// 库房
		list.setUser_id(request.getParameter("user_id")!=null?Long.parseLong(request.getParameter("user_id")):null);
		list.setType_id(request.getParameter("type_id")!=null?Long.parseLong(request.getParameter("type_id")):null);
		list.setSupply_id(request.getParameter("supply_id")!=null?Long.parseLong(request.getParameter("supply_id")):null);
		//判断是否带有一维码
		if(list.Type().getIscode()==UtilEnum.Type_Iscode.Iscode.getValue())
		{//是
			java.util.List<String> lists = (java.util.List<String>) session.getAttribute("code");
			java.util.List<Code> codes = new ArrayList<Code>();;
			if(lists!=null)//一维码封装到codes中
			{
				for (String string : lists) {
					String[] s = StringUtils.split(string, " ");
					Code code = new Code();
					code.setNumber(s[0]);
					codes.add(code);
				}
			}
			
			if(listService.add(list, codes ))
			{
				printHtml("操着成功！");
			}
			else {
					printHtml("失败！");
			}
		}else {
			if(listService.add(list, null))
			{
				printHtml("操着成功！");
			}
			else {
					printHtml("失败！");
			}
		}
		
	}
	
	/**
	 * 取得一维码
	 */
	public void getCode()
	{
		
		
		java.util.List<String> codes = (java.util.List<String>) session.getAttribute("code");
		if(codes==null)
		{
			JsonArray array = new JsonArray();
			JsonObject jsonObject = new JsonObject();
			jsonObject.addProperty("name", "无");
			array.add(jsonObject);
			printJson(array.toString());
			 return;
			 }
		JsonArray array = new JsonArray();
		for (String string : codes) {
			String[] s = StringUtils.split(string, " ");
			JsonObject jsonObject = new JsonObject();
			jsonObject.addProperty("name", s[0]);
			//jsonObject.addProperty("number", s[1]);
			array.add(jsonObject);
		}
		
		printJson(array.toString());

	}
	
	public void readyCode()
	{
		
		
		try {
			//MultipartParser mp = new MultipartParser(request, 10*1024*1024);// 10MB
			MultipartParser mp =new MultipartParser(request, 10*1024*1024, true, true, "UTF-8");
			 Part part;
		      while ((part = mp.readNextPart()) != null) {
		        String name = part.getName();
		        if (part.isParam()) {
		          // it's a parameter part
		        }
		        else if (part.isFile()) {
		          // it's a file part
		          FilePart filePart = (FilePart) part;
		          String fileName = filePart.getFileName();
		          if (fileName != null) {
		            File dir=new File("ywm.txt");
		            if(!dir.exists())
		            	dir.createNewFile();
					// the part actually contained a file
		             filePart.writeTo(dir);
		           
		            
		           java.util.List<String> authentication= FileUtils.readLines(dir);
		           for (String string : authentication) {
		        	   									System.out.println(string );
		           								}
		           session.setAttribute("code", authentication);
		        	  				//printJson("");
		        	  //printHtml(authentication);
		          }
		          
		        
		        }
		      }
		} catch (IOException e) {

			e.printStackTrace();
		} 
		
	}
	
	
	public void list()
	{
		//listService.	
		PageUtil pageutil= new PageUtil();
		if(StringUtils.isNotBlank(status))
		{
				pageutil= 	listService.getLists(Integer.parseInt(status), page, limit);
		}else {
			 pageutil=listService.getListt(Integer.parseInt(type), page, limit);
		}
		JsonObject jsonObject = new JsonObject();
		jsonObject.addProperty("totalCount", pageutil.getTotalpage());
		
		JsonArray jsonArray= new JsonArray();
		java.util.List<List> lists=(java.util.List<List>) pageutil.getList();
		//封装list中的json
		for (List list : lists) {
			Gson gson = new Gson();
			JsonElement element =gson.toJsonTree(list);
			JsonObject json = element.getAsJsonObject();
			json.addProperty("admin_id", list.Admin()!=null?list.Admin().getName():"");//管理员
			json.addProperty("user_id", list.User()!=null?list.User().getName():"");//用户
			json.addProperty("type_id", list.Type()!=null?list.Type().getName():"");//类型
			json.addProperty("supply_id", list.Supply()!=null?list.Supply().getName():"");//类型
			jsonArray.add(json);
		}
		
		jsonObject.add("resultList", jsonArray);
		DBManager.closeConnection();
		printJson(jsonObject.toString());
	}
//	public void listt()
//	{
//		//listService.	
//		PageUtil pageutil=listService.getListt(type, page, limit);
//		JsonObject jsonObject = new JsonObject();
//		jsonObject.addProperty("totalCount", pageutil.getTotalpage());
//		Gson gson = new Gson();
//		jsonObject.add("resultList", gson.toJsonTree(pageutil.getList()));
//		DBManager.closeConnection();
//		printJson(jsonObject.toString());
//	}
	
	
	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}


	public String getStatus() {
		return status;
	}


	public void setStatus(String status) {
		this.status = status;
	}


	public String getType() {
		return type;
	}


	public void setType(String type) {
		this.type = type;
	}

	public List getList() {
		return list;
	}

	public void setList(List list) {
		this.list = list;
	}

	
	
}
